import VGE from '../../VGE';
import { Camera } from './Camera';
import { Misc } from './Misc';

export default class BMapApp {
	static async open(sceneData = {}) {
		try {
			const {
				sceneUrl,
				container,
				cameraParams = {},
				homeView = {},
				token,
				loadOptions = {}
			} = sceneData;
			await VGE.util.findOrCreateDom(container);
			this.BMapGL = await this.loadScript({ sceneUrl, token });

			const options = Object.assign(
				{ enableWheelZoom: true, preserveDrawingBuffer: true },
				loadOptions
			);
			this.viewer = new this.BMapGL.Map(container, options);

			this.homeViewParams = homeView;

			this.camera = new Camera(this.viewer);
			this.misc = new Misc(this.viewer);

			this.camera.flyTo(cameraParams);

			return this.viewer;
		} catch (e) {
			console.log(e.message);
		}
	}

	static async loadScript({ sceneUrl, token }) {
		// 加载百度地图
		if (window.BMapGL) return Promise.resolve(window.BMapGL);
		return new Promise((resolve, reject) => {
			const script = document.createElement('script');
			script.src = `${sceneUrl}&ak=${token}`;
			script.onload = () => resolve(window.BMapGL);
			script.onerror = reject;
			document.body.appendChild(script);
		});
	}

	static async close() {
		if (this.viewer) {
			this.viewer.destroy();
			this.viewer.container.innerHTML = '';
		}
	}
}
BMapApp.viewer = null;
BMapApp.homeViewParams = {};
BMapApp.camera = null;
BMapApp.misc = null;
